package com.hualife.md.team.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hualife.md.common.dao.mybatis.entity.DefKv;
import com.hualife.md.common.dao.mybatis.mapper.DefKvMapper;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.util.HttpUtil;
import com.hualife.support.util.JsonUtil;


@Service("wechatTagInterface")
public class WechatTagInterface {
	private static final Logger logger = LoggerFactory
			.getLogger(WechatTagInterface.class);
	
	@Autowired
	private DefKvMapper defKvMapper;


	/**
	 * 查询标签下的用户信息
	 * 
	 * @param tagId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> queryTagUser(String tagId, String token) {
		DefKv kv = defKvMapper.selectByPrimaryKey("wx.tag.get");
		if (kv == null) {
			throw new BusinessException("创建标签失败，未查询到创建企业号标签配置信息");
		}

		Map<String, Object> map = new HashMap<String, Object>();
		String url = kv.getV() + "?access_token=" + token + "&tagid=" + tagId;
		try {
			String resultJson = HttpUtil.get(url);
			if (resultJson ==null || "".equals(resultJson.trim())) {
				logger.info("创建标签失败，未返回数据");
				throw new BusinessException("创建标签失败，企业号未返回数据！");
			}
			map = JsonUtil.jackson2Map(resultJson);
			return map;
		} catch (Exception e) {
			logger.info("查询标签下用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	
	public void deleteTagUser(String token, Map<String, Object> paraMap) {
		DefKv kv = defKvMapper.selectByPrimaryKey("wx.tag.deluser");
		if (kv == null) {
			throw new BusinessException("创建标签失败，未查询到创建企业号标签配置信息");
		}

		String url = kv.getV() + "?access_token=" + token;
		try {
			String resultJson = HttpUtil.post(url, JsonUtil.objectToJackson(paraMap), 20000);
			if (resultJson ==null || "".equals(resultJson.trim())) {
				logger.info("创建标签失败，未返回数据");
				throw new BusinessException("创建标签失败，企业号未返回数据！");
			}
		} catch (Exception e) {
			logger.info("查询标签下用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
		}
	}
	
	public void addTagUser(String token, Map<String, Object> paraMap) {
		DefKv kv = defKvMapper.selectByPrimaryKey("wx.tag.adduser");
		if (kv == null) {
			throw new BusinessException("创建标签失败，未查询到创建企业号标签配置信息");
		}

		String url = kv.getV() + "?access_token=" + token;
		try {
			String resultJson = HttpUtil.post(url, JsonUtil.objectToJackson(paraMap), 20000);
			if (resultJson ==null || "".equals(resultJson.trim())) {
				logger.info("创建标签失败，未返回数据");
				throw new BusinessException("创建标签失败，企业号未返回数据！");
			}
		} catch (Exception e) {
			logger.info("查询标签下用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
		}
	}
}
